package com.htstar.ovms.device.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.htstar.ovms.common.core.constant.SecurityConstants;
import com.htstar.ovms.common.core.util.R;
import com.htstar.ovms.common.log.annotation.SysLog;
import com.htstar.ovms.common.security.annotation.Inner;
import com.htstar.ovms.device.api.entity.DeviceLastData;
import com.htstar.ovms.device.api.feign.DeviceGatewayFeign;
import com.htstar.ovms.device.api.wrapper.OTAData;
import com.htstar.ovms.device.service.DeviceLastDataService;
import com.htstar.ovms.device.service.DeviceService;
import com.htstar.ovms.device.service.OTAUpdateService;
import com.htstar.ovms.msg.api.constant.MsgTypeConstant;
import com.htstar.ovms.msg.api.entity.MsgPushLog;
import com.htstar.ovms.msg.api.feign.MsgAppPushFeign;
import com.htstar.ovms.msg.api.req.BroadAppPushByEtpReq;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * 设备最新状态
 *
 * @author 范利瑞
 * @date 2020-06-20 16:42:12
 */
@RestController
@AllArgsConstructor
@RequestMapping("/devicelastdata")
@Api(value = "devicelastdata", tags = "设备最新状态管理/Equipment latest state management")
public class DeviceLastDataController {

    private final DeviceLastDataService deviceLastDataService;

    private final DeviceService deviceService;

    private final MsgAppPushFeign msgAppPushFeign;

    private final RedisTemplate redisTemplate;

    private final DeviceGatewayFeign deviceGatewayFeign;

    private final OTAUpdateService otaUpdateService;


    /**
     * 由心跳监听发现的设备下线
     *
     * @param deviceSn
     * @param online
     */
    @Inner
    @GetMapping("/heartBeatOnline/{deviceSn}/{online}")
    void heartBeatOnline(@PathVariable("deviceSn") String deviceSn, @PathVariable("online") Integer online) {
        deviceLastDataService.updateOnline(deviceSn, online);
    }

    /**
     * 分页查询
     *
     * @param page           分页对象
     * @param deviceLastData 设备最新状态
     * @return
     */
    @ApiOperation(value = "分页查询/Paging query", notes = "分页查询")
    @GetMapping("/page")
    public R getDeviceLastDataPage(Page page, DeviceLastData deviceLastData) {
        return R.ok(deviceLastDataService.page(page, Wrappers.query(deviceLastData)));
    }


    /**
     * 通过id查询设备最新状态
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询/Query by id", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(deviceLastDataService.getById(id));
    }

    /**
     * 通过sn查询设备最新状态
     */
    @ApiModelProperty(value = "通过SN查询/Query by SN", notes = "通过SN查询")
    @GetMapping("/bySn/{id}")
    public R getBySN(@PathVariable("id") String id) {
        return R.ok(deviceLastDataService.getOne(Wrappers.<DeviceLastData>lambdaQuery()
                .eq(DeviceLastData::getDeviceSn, id)));
    }

    /**
     * 通过carId查询设备最新状态
     */
    @ApiModelProperty(value = "通过carId查询设备最新状态/Query the latest status of the device through car Id", notes = "通过carId查询设备最新状态")
    @GetMapping("/byCarId/{carId}")
    public R byCarId(@PathVariable("carId") String carId) {
        DeviceLastData one = deviceLastDataService.byCarId(carId);
        return R.ok(one);
    }

    /**
     * 新增设备最新状态
     *
     * @param deviceLastData 设备最新状态
     * @return R
     */
    @ApiOperation(value = "新增设备最新状态/The latest status of new equipment", notes = "新增设备最新状态")
    @SysLog("新增设备最新状态")
    @PostMapping
    public R save(@RequestBody DeviceLastData deviceLastData) {
        return R.ok(deviceLastDataService.save(deviceLastData));
    }

    /**
     * 修改设备最新状态
     *
     * @param deviceLastData 设备最新状态
     * @return R
     */
    @ApiOperation(value = "修改设备最新状态/Modify the latest state of the device", notes = "修改设备最新状态")
    @SysLog("修改设备最新状态")
    @PutMapping
    public R updateById(@RequestBody DeviceLastData deviceLastData) {
        return R.ok(deviceLastDataService.updateById(deviceLastData));
    }

    /**
     * 通过id删除设备最新状态
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除设备最新状态/delete the latest state of the device by id", notes = "通过id删除设备最新状态")
    @SysLog("通过id删除设备最新状态")
    @DeleteMapping("/{id}")
    public R removeById(@PathVariable Integer id) {
        return R.ok(deviceLastDataService.removeById(id));
    }


    @GetMapping("/deviceCheck")
    @Inner
    public void deviceCheck() {
        QueryWrapper<DeviceLastData> wrapper = new QueryWrapper<>();
        ArrayList<Integer> online = new ArrayList<>();
        online.add(0);
        online.add(1);
        wrapper.in("online", online);
        LocalDateTime now = LocalDateTime.now().minusDays(1);
//        LocalDateTime now = LocalDateTime.now().minusMinutes(11);

        wrapper.lt("update_time", now);
        List<DeviceLastData> list = deviceLastDataService.list(wrapper);
        for (DeviceLastData deviceLastData : list) {
            deviceLastData.setOnline(3);
            deviceLastData.setUpdateTime(null);
            String deviceSn = deviceLastData.getDeviceSn();
            String licCode = deviceService.getLicCode(deviceSn);
            licCode = deviceService.getLicCode(deviceSn);
            licCode = deviceService.getLicCode(deviceSn);
            //推送报警
            BroadAppPushByEtpReq sing = new BroadAppPushByEtpReq(); //企业推送对象
            Integer carId = deviceService.getCarId(deviceSn);
            sing.setAppCarId(carId);
            sing.setRemindType(3);
            int etpIds = deviceService.getEtpIds(deviceSn);
            sing.setEtpId(etpIds);
            //消息提醒
            sing.setMsgType(MsgTypeConstant.REMINDER_MESSAGE);
            sing.setTitle("设备异常提醒");
            sing.setContent("【" + licCode + "】疑似设备异常，请及时确认！");
            try {
                deviceLastDataService.updateById(deviceLastData);//更新状态再推送消息
                msgAppPushFeign.EdpIdtoSingdemos(sing, SecurityConstants.FROM_IN);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
//        DeviceLastData deviceLastData = new DeviceLastData();
//        deviceLastData.setOnline(2);
//        通过set给值没法自动更新update_time
//        deviceLastDataService.update(null, Wrappers.<DeviceLastData>lambdaUpdate().eq(DeviceLastData::getDeviceSn, "45785885").set(DeviceLastData::getOnline, 1));
//        deviceLastDataService.update(deviceLastData, Wrappers.<DeviceLastData>lambdaUpdate().eq(DeviceLastData::getDeviceSn, "45785885"));
//        deviceLastDataService.lambdaUpdate().eq(DeviceLastData::getDeviceSn, "45785885").update(deviceLastData);
    }

    @GetMapping("/obdOtaUpdate")
    @Inner
    public void obdOtaUpdate() {
//        String otaCommandData = (String) redisTemplate.opsForValue().get("OTAData");
//        String noOnlineList = (String) redisTemplate.opsForValue().get("OTANoOnlineList");
//        if ("".equals(noOnlineList)) {
//            return;
//        }
//        String[] split = noOnlineList.split(",");
//        List<String> noOnlineDeviceSnList = Arrays.asList(split);//暂未上线列表
//        List<String> needToList = deviceLastDataService.getNeedToList(noOnlineDeviceSnList);
//        //取消holdON状态
////        otaUpdateService.updateHoldOn(needToList, 0);
//        //更新doldOn列表
//        noOnlineDeviceSnList.removeAll(needToList);
//        if (noOnlineDeviceSnList.size() == 0) {
//            redisTemplate.opsForValue().set("OTANoOnlineList", "");
//        } else {
//            StringBuffer stringBuffer = new StringBuffer();
//            for (String deviceSn : noOnlineDeviceSnList) {
//                stringBuffer.append(deviceSn).append(",");
//            }
//            String s = stringBuffer.toString();
//            String substring = s.substring(0, s.length() - 1);
//            redisTemplate.opsForValue().set("OTANoOnlineList", substring);
//        }
//
//        OTAData otaData = new OTAData();
//        otaData.setDeviceSnList(needToList);
//        otaData.setData(otaCommandData);
//        deviceGatewayFeign.updateBatch(otaData);//  下发指令
    }
}
